package com.example.testhiber.initPackage.business.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.testhiber.initPackage.business.Dictionaries.IdType;
import com.example.testhiber.initPackage.business.Dictionaries.Period;
import com.example.testhiber.initPackage.business.Dictionaries.StaticVar;
import com.example.testhiber.initPackage.business.Dictionaries.TrackType;
import com.example.testhiber.initPackage.business.utils.JsoupUtils;
import com.example.testhiber.initPackage.business.utils.StringKit;
import com.github.binarywang.java.emoji.EmojiConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("jsoup")
public class JsoupController {
    private static final Logger logger = LoggerFactory.getLogger(JsoupController.class);
    private static final String PATH="/test/";

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    private static Integer wifimactj=0;

//    /**
//     * 首页跳转
//     * @return
//     */
    @ResponseBody
    @RequestMapping("/index")
    public ModelAndView sayHello(){
        ModelAndView mav = new ModelAndView();

        try {
            String sql = "select * from mobile where deleted='0'";
            List<Map<String,Object>> maps = jdbcTemplate.queryForList(sql);
            for(Map<String,Object> m:maps){
                String sjh = StringKit.toString(m.get("mobile"));
                String uname = StringKit.toString(m.get("uname"));
                String res = JsoupUtils.getTxl(sjh);
                String res2 = JsoupUtils.getTxlFx(sjh);

                if(!"".equals(StringKit.toString(res))){
                    JSONObject txlJson = JSONObject.parseObject(res);
                    String childRes = StringKit.toString(txlJson.get("children"));
                    if(!"".equals(StringKit.toString(childRes))){
                        JSONArray childArr = JSONArray.parseArray(childRes);
                        System.out.println("childArr:"+childArr);
                        for(Object o:childArr){
                            JSONObject phoneObj = JSONObject.parseObject(StringKit.toString(o));
                            String phone = StringKit.toString(phoneObj.get("phone"));
                            String label = StringKit.toString(phoneObj.get("label"));
                            System.out.println("phone："+phone);
                            System.out.println("label："+label);
                            EmojiConverter emojiConverter = EmojiConverter.getInstance();
                            label= emojiConverter.toAlias(label);//将聊天内容进行转义
                            label = label.replace( "\'","\\\'");//处理斜杠

                            String sql2 = " INSERT INTO `txl1` (`sjh`, `bz`, `lsdh`) " +
                                    "VALUES " +
                                    "('"+ phone +"',' "+ label +"',' "+ sjh +"'); ";
                            jdbcTemplate.execute(sql2);

                        }
                    }
                }

                if(!"".equals(StringKit.toString(res2))){
                    JSONObject txlfxJson = JSONObject.parseObject(res2);
                    String child2Res = StringKit.toString(txlfxJson.get("children"));
                    if(!"".equals(StringKit.toString(child2Res))){
                        JSONArray child2Arr = JSONArray.parseArray(child2Res);
                        System.out.println("child2Arr:"+child2Arr);
                        for(Object o:child2Arr){
                            JSONObject phoneObj = JSONObject.parseObject(StringKit.toString(o));
                            String phone = StringKit.toString(phoneObj.get("phone"));
                            String label = StringKit.toString(phoneObj.get("label"));
                            System.out.println("phone："+phone);
                            System.out.println("label："+label);

                            EmojiConverter emojiConverter = EmojiConverter.getInstance();
                            label= emojiConverter.toAlias(label);//将聊天内容进行转义
                            label = label.replace( "\'","\\\'");//处理斜杠

                            String sql2 = " INSERT INTO `txl2` (`sjh`, `bz`, `lsdh`) " +
                                    "VALUES " +
                                    "('"+ phone +"', '"+ label +"', '"+ sjh +"'); ";
                            jdbcTemplate.execute(sql2);
                        }
                    }
                }

                String updateSql = "update mobile set deleted=1 where uname='"+uname+"' and mobile='" +sjh +"'" ;
                jdbcTemplate.execute(updateSql);
            }

        }catch (Exception e){
            e.printStackTrace();
        }


        mav.setViewName(PATH+"index");
        return mav;
    }


    //根据wifi获取手机号
    @ResponseBody
    @RequestMapping("/getPhoneByWifi")
    public ModelAndView getPhoneByWifi(){
        ModelAndView mav = new ModelAndView();

        try {
            String sql = "  select * from phone where LENGTH(phone)=11 and deleted=0 ";
            List<Map<String,Object>> maps = jdbcTemplate.queryForList(sql);

            if(maps!=null && maps.size()>0){
                for(Map<String,Object> m : maps){
                    String phone = StringKit.toString(m.get("phone"));
                    String titleRes = JsoupUtils.getTitle(IdType.phone,phone);//根据手机号获取标签
                    System.out.println("循环第一层："+phone+",结果："+titleRes);
                    //deviceId todo 将标签获取的deviceid 得到 然后遍历
//                    [{"deviceId":"0ecf9b58ebd80bd6238b2e5be79967bbbd57c169","imei":"869011022948043","imsi":"","mac":"4a:45:b1:69:76:c4","phone":"13381176901","snsuid":null,"idfa":null,"time":1525536000},{"deviceId":"f7bf17bbff41dbb76432af7e6390d8925bc13efc","imei":"869011022948043","imsi":"","mac":"","phone":"13381176901","snsuid":null,"idfa":null,"time":1525536000}]
                    List<String> deviceList = new ArrayList<>();
                    if(!"".equals(StringKit.toString(titleRes))){
                        JSONArray titleArray = JSONArray.parseArray(titleRes);
                        for (Object o:titleArray){
                            JSONObject jsonObject = JSONObject.parseObject(StringKit.toString(o));
                            String deviceId = StringKit.toString(jsonObject.get("deviceId"));
                            deviceList.add(deviceId);
                            System.out.println("循环第二层，获取deviceId："+phone+",结果："+deviceId);
                        }
                        //根据标签循环获取轨迹
                        if(deviceList!=null && deviceList.size()>0){
                            for (String deviceId:deviceList){
//        {"total":207,"pageNum":1,"pageSize":99,"list":[
//        {"begintime":"2020-05-27 20:08","endtime":"2020-05-27 20:08","lat":"31.823612","lon":"120.001876","name":"","orig_note1":"34:96:72:d4:27:1f","orig_note2":"xd","trajectoryType":"wifi","type":"Wi-Fi连接","source":null,"hasLabel":false},{"begintime":"2020-05-26 07:24","endtime":"2020-05-26 07:24","lat":"31.823612","lon":"120.001876","name":"","orig_note1":"34:96:72:d4:27:1f","orig_note2":"xd","trajectoryType":"wifi","type":"Wi-Fi连接","source":null,"hasLabel":false},{"begintime":"2020-02-22 21:37","endtime":"2020-02-22 21:37","lat":"31.686184","lon":"119.803106","name":"","orig_note1":"a8:57:4e:1c:9f:90","orig_note2":"TP-LINK_1C9F90","trajectoryType":"wifi","type":"Wi-Fi连接","source":null,"hasLabel":false}]}
                                String gjStr = JsoupUtils.getGj(deviceId,StaticVar.startTime,StaticVar.endTime,Period.ywgj,TrackType.LOCATION_0,"0","999");
                                System.out.println("循环第三层，获取轨迹deviceId："+deviceId+",结果："+gjStr);
                                if(!"".equals(StringKit.toString(gjStr))){
                                    JSONObject gjObj = JSONObject.parseObject(gjStr);
                                    String gjJsonArrgjStr = StringKit.toString(gjObj.get("list"));
                                    System.out.println("循环第四层，获取轨迹json："+",结果："+gjJsonArrgjStr);
                                    if(!"".equals(StringKit.toString(gjJsonArrgjStr))){
                                        JSONArray gjJsonArr = JSONArray.parseArray(gjJsonArrgjStr);
//                                        gjJsonArr.
                                        //todo  通过轨迹 拿到WiFimac  当type为wifi，orig_note1为wifimac
//                                        提交wifi申请之后的 返回结果 "1287689910505398273"
                                        for(Object o :gjJsonArr){
                                            JSONObject gjJsonObj = JSONObject.parseObject(StringKit.toString(o));
                                            String wifimac = StringKit.toString(gjJsonObj.get("orig_note1"));//wifimac
                                            String type = StringKit.toString(gjJsonObj.get("trajectoryType"));//wifi类型
                                            System.out.println("循环第五层，获取wifimac："+wifimac+",type："+type);
                                            if("wifi".equals(type)){
                                                String tjWifiCxRes = JsoupUtils.tjWifiCx(IdType.mac,wifimac, StaticVar.wifiStartTime,StaticVar.wifiEndTime);
                                                tjWifiCxRes = StringKit.stringReplace(tjWifiCxRes);
                                                if(!"".equals(StringKit.toString(tjWifiCxRes))){
                                                    //存库提交记录 轮询获取数据
                                                    String sql2 = " INSERT INTO `wifi_record` " +
                                                            "(`cxrwjg`, `deleted`, `starttime`, `endtime`, `exid`, `idtype`, `hisphone`) " +
                                                            "VALUES " +
                                                            "(" +
                                                            "'"+ tjWifiCxRes +"','0','"+ StaticVar.wifiStartTime +"','"+ StaticVar.wifiEndTime +"','"+ IdType.mac +"','"+ wifimac +"','"+ phone +"'"+
                                                            ")";
                                                    jdbcTemplate.execute(sql2);

                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                    }




                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }


        mav.setViewName(PATH+"index");
        return mav;
    }


}